<!--陪玩列表页-->
<template>
  <el-container>
    <el-header height="8vh" style="padding: 10px 20px;background-color: #fff;overflow:hidden;">
      <span style="line-height: 60px;font-size: 20px;">陪玩管理</span>
      <el-form :inline="true" style="float: right;margin-top: 10px;">
        <el-form-item label="店家选择" style="width: 220px;">
          <el-select v-model="escortQuery.shopId"
                     placeholder="请选择店家" @change="loadEscort">
            <el-option v-for="shop in merchant.shopList"
                       :label="shop.shopName" :value="shop.id"/>
          </el-select>
        </el-form-item>
      </el-form>
    </el-header>

    <el-main style="padding: 0;">
      <el-card style="height: 70px;margin: 20px;">
        <el-form :inline="true">
          <el-form-item label="陪玩是否展示" style="width: 220px;">
            <el-select v-model="escortQuery.visible"
                       placeholder="请选择" @change="loadEscort">
              <el-option v-for="item in visibleEnum"
                         :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="primary" @click="loadEscort">查询</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <el-card style="margin: 20px;">
        <div style="margin:10px 0px 40px 10px;">
          陪玩列表
          <el-button style="float: right;margin-top:-3px;" type="primary"
                     @click="showAddEscort">
            新增陪玩
          </el-button>
        </div>
        <el-table
            :data="escortList"
            style="width: 100%">
          <el-table-column align="center" label="序号" type="index" width="80"/>
          <el-table-column align="center" label="陪玩用户名" prop="username"/>
          <el-table-column align="center" label="陪玩介绍" prop="description"/>
          <el-table-column align="center" label="陪玩价格（元/小时）" prop="price"
                           width="100"/>
          <el-table-column align="center" label="粉丝人数" prop="fansNum"/>
          <el-table-column align="center" label="手机号" prop="phone"/>
          <el-table-column align="center" label="陪玩标签" prop="tagNameString"/>
          <el-table-column :formatter="workingHoursFormatter" align="center"
                           label="工作时间"/>
          <el-table-column :formatter="visibleFormatter" align="center"
                           label="是否展示" prop="visible"/>
          <el-table-column align="center" label="平均评分" prop="avgRating"
                           width="80"/>
          <el-table-column align="center" label="月订单数" prop="orderNum"
                           width="80"/>
          <el-table-column align="center" label="操作" width="150">
            <template #default="scope">
              <el-button link type="primary"
                         @click="showEditEscort(scope.row.id)">编辑
              </el-button>
              <el-button link type="primary"
                         @click="showEscortDetail(scope.row)">详情
              </el-button>
              <el-button link type="danger"
                         @click="deleteEscort(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-main>
  </el-container>

  <el-dialog
      v-model="showDialogVisible"
      :before-close="closeShowDialog"
      style="padding: 40px;"
      title="陪玩详情"
      width="1000px">
    <el-descriptions :column="2" border direction="horizontal">
      <el-descriptions-item label="陪玩id">
        {{ escortDetail.id }}
      </el-descriptions-item>
      <el-descriptions-item label="用户id">
        {{ escortDetail.userId }}
      </el-descriptions-item>

      <el-descriptions-item label="陪玩用户名">
        {{ escortDetail.username }}
      </el-descriptions-item>
      <el-descriptions-item label="陪玩标签">
        {{ escortDetail.tagNameString || null }}
      </el-descriptions-item>

      <el-descriptions-item label="陪玩描述">
        {{ escortDetail.description || null }}
      </el-descriptions-item>
      <el-descriptions-item label="陪玩价格（元/小时）">
        {{ escortDetail.price || null }}
      </el-descriptions-item>

      <el-descriptions-item label="陪玩年龄">
        {{ escortDetail.age || null }}
      </el-descriptions-item>
      <el-descriptions-item label="陪玩性别">
        {{ getEscortGender || null }}
      </el-descriptions-item>

      <el-descriptions-item label="陪玩邮箱">
        {{ escortDetail.email || null }}
      </el-descriptions-item>
      <el-descriptions-item label="陪玩手机号">
        {{ escortDetail.phone || null }}
      </el-descriptions-item>

      <el-descriptions-item label="陪玩身高">
        {{ escortDetail.height || null }}
      </el-descriptions-item>
      <el-descriptions-item label="陪玩体重">
        {{ escortDetail.weight || null }}
      </el-descriptions-item>

      <el-descriptions-item label="陪玩生日">
        {{ escortDetail.birthday || null }}
      </el-descriptions-item>
      <el-descriptions-item label="个性签名">
        {{ escortDetail.signature || null }}
      </el-descriptions-item>

      <el-descriptions-item label="用户头像">
        <el-image v-if="escortDetail?.imgUrl"
                  :initial-index="4"
                  :max-scale="7"
                  :min-scale="0.2" :preview-src-list="[escortDetail.imgUrl]"
                  :src="escortDetail.imgUrl"
                  :zoom-rate="1.2" fit="contain"
                  style="width: 250px; height: 150px"/>
      </el-descriptions-item>
      <el-descriptions-item label="展示照片">
        <el-image v-if="escortDetail?.imgUrlList
        && escortDetail.imgUrlList.length > 0"
                  :initial-index="4"
                  :max-scale="7"
                  :min-scale="0.2" :preview-src-list="escortList.imgUrlList"
                  :src="escortDetail.imgUrlList[0]"
                  :zoom-rate="1.2" fit="contain"
                  style="width: 250px; height: 150px"/>
      </el-descriptions-item>

      <el-descriptions-item label="工作时间">
        {{ escortDetail.workingHoursFrom || null }}
        - {{ escortDetail.workingHoursTo || null }}
      </el-descriptions-item>
      <el-descriptions-item label="是否展示">
        {{ getEscortVisible }}
      </el-descriptions-item>

      <el-descriptions-item label="加入时间">
        {{ escortDetail.createTime }}
      </el-descriptions-item>
      <el-descriptions-item label="平均评分">
        {{ escortDetail.avgRating || null }}
      </el-descriptions-item>

      <el-descriptions-item label="月订单数">
        {{ escortDetail.orderNum || null }}
      </el-descriptions-item>
      <el-descriptions-item label="点赞数">
        {{ escortDetail.likes || null }}
      </el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <el-button @click="closeShowDialog">返回</el-button>
    </template>
  </el-dialog>

  <el-dialog
      v-model="editDialogVisible"
      :before-close="handleCloseEdit"
      :title="isAdd ? '新陪玩录入' : '编辑陪玩信息'"
      style="padding: 40px;"
      width="1000px">
    <el-form label-position="top" label-width="80px">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="陪玩id">
            <el-input v-model="escortDetail.id" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户id">
            <el-input v-model="escortDetail.userId" :disabled="!isAdd"
                      placeholder="请输入用户id"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="陪玩介绍">
            <el-input v-model="escortDetail.description"
                      placeholder="请输入陪玩介绍"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="陪玩价格（元/小时）">
            <el-input v-model="escortDetail.price"
                      placeholder="请输入陪玩价格"
                      step="0.01" type="number"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="工作时间">
            <el-time-picker v-model="escortDetail.timeRange"
                            end-placeholder="结束" is-range="is-range"
                            start-placeholder="开始" value-format="HH:mm"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否展示">
            <el-radio-group v-model="escortDetail.visible">
              <el-radio v-for="item in visibleEnum"
                        :label="item.label" :value="item.value"/>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="展示照片">
            <el-upload
                v-model:file-list="imgList"
                :action="uploadAction" :on-preview="handlePictureCardPreview"
                :on-remove="handlePictureRemove"
                :on-success="pictureAdd"
                list-type="picture-card">
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleCloseEdit">取消</el-button>
      <el-button type="primary"
                 @click="saveEscort">保存信息
      </el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="imageDialogVisible">
    <img :src="dialogImageUrl" alt="Preview Image"/>
  </el-dialog>
</template>

<script setup>
import {computed, onMounted, ref} from "vue";
import {ElMessage} from "element-plus";
import axios from "axios";
import qs from "qs";

const merchant = ref({
  shopList: [],
});
const escortQuery = ref({
  shopId: null,
  visible: null,
})
const escortList = ref([])
let tagIdSet = new Set();
const tagList = ref([])
const visibleEnum = ref([
  {label: '展示', value: '1'},
  {label: '不展示', value: '0'},
])
const genderEnum = ref([
  {label: '男', value: '1'},
  {label: '女', value: '0'},
])
const escortDetail = ref({});
const showDialogVisible = ref(false);
const editDialogVisible = ref(false);
const isAdd = ref(false);
const imgList = ref([]);
const uploadAction = ref(BASE_URL + 'v1/file/upload');
const imageDialogVisible = ref(false);
const dialogImageUrl = ref('');

onMounted(() => {
  getMerchant(merchant);
});
const loadEscort = () => {
  if (escortQuery.value.shopId == null) {
    ElMessage.info("请选择店家");
    return;
  }
  axios.get(BASE_URL + 'v1/show/escort/select',
      {params: escortQuery.value})
      .then(res => {
        if (res.data.code === 2000) {
          escortList.value = res.data.data;
          setTagNameString(escortList.value);
        } else {
          ElMessage.error(res.data.msg);
        }
      });
}
const setTagNameString = async (escortArr) => {
  if (escortArr == null || escortArr.length === 0) {
    return;
  }
  for (let room of escortArr) {
    if (room.tagIdList == null || room.tagIdList.length === 0) {
      continue;
    }
    tagIdSet =
        new Set([...tagIdSet, ...room.tagIdList]);
  }
  if (tagIdSet.size !== tagList.value.length) {
    await updateTagEnum();
  }
  for (let escort of escortArr) {
    // console.log(tagList);
    if (escort.tagIdList == null || escort.tagIdList.length === 0) {
      continue;
    }
    escort.tagNameList = [];
    for (let id of escort.tagIdList) {
      let name = getTagName(id);
      if (!name) {
        continue;
      }
      escort.tagNameList.push(name);
    }
    escort.tagNameString = escort.tagNameList.join(',');
    // console.log(room.tagNameList);
  }
}
const updateTagEnum = async () => {
  // console.log(tagIdSet);
  let data = {tagIdList: tagIdSet.size ? [...tagIdSet] : []};
  // console.log(data);
  try {
    let res = await axios.get(BASE_URL + 'v1/show/tag/select/ids',
        {
          params: data, paramsSerializer:
              params => qs.stringify(params, {indices: false})
        });
    if (res.data.code === 2000) {
      tagList.value = res.data.data;
      // console.log('tagList');
      // console.log(tagList.value);
    } else {
      ElMessage.error(res.data.msg);
    }
  } catch (error) {
    ElMessage.error(error.message);
  }
}
const getTagName = (id) => {
  // console.log(id);
  // console.log(tagList.value);
  if (!tagList.value) {
    return null;
  }
  for (let tag of tagList.value) {
    if (tag.id === id) {
      return tag.label;
    }
  }
  return null;
}
const resetSearch = () => {
  escortQuery.value.visible = null;
  loadEscort();
}
const workingHoursFormatter = (row, column, cellValue, index) => {
  const start = row.workingHoursFrom;
  const end = row.workingHoursTo;
  return `${start} - ${end}`;
}
const visibleFormatter = (row, column, cellValue, index) => {
  return cellValueFormatter(cellValue, visibleEnum);
}
const showAddEscort = () => {
  if (escortQuery.value.shopId == null) {
    ElMessage.info("请选择店家");
    return;
  }
  isAdd.value = true;
  editDialogVisible.value = true;
  escortDetail.value = {
    shopId: escortQuery.value.shopId,
    visible: '0',
    tagIdList: [],
    tagNameList: [],
    imgUrlList: [],
  }
}
const showEditEscort = async (id) => {
  let res = await axios.get(BASE_URL + 'v1/show/escort/select',
      {params: {id: id}});
  if (res.data.code === 2000) {
    let escortArr = res.data.data;
    await setTagNameString(escortArr);
    escortDetail.value = escortArr[0];
    // console.log(roomDetail.value);
  } else {
    ElMessage.error(res.data.msg);
    return;
  }
  escortDetail.value.timeRange = [
    escortDetail.value.workingHoursFrom,
    escortDetail.value.workingHoursTo
  ];
  // console.log(roomDetail.value.timeRange);
  let list = escortDetail.value.imgUrlList;
  // console.log(list);
  if (list != null && list.length > 0) {
    for (let imgUrl of list) {
      if (imgUrl != null && imgUrl.trim() !== '') {
        imgList.value.push({
          name: imgUrl,
          url: imgUrl,
        })
      }
    }
  }
  editDialogVisible.value = true;
}
const showEscortDetail = (row) => {
  escortDetail.value = row;
  showDialogVisible.value = true;
}
const deleteEscort = (row) => {
  if (!confirm('是否删除陪玩：' + row.username + '？')) {
    return;
  }
  axios.post(BASE_URL + 'v1/show/escort/delete/' + row.id)
      .then(res => {
        if (res.data.code === 2000) {
          ElMessage.success('已删除');
          loadEscort();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
}
const closeShowDialog = () => {
  showDialogVisible.value = false;
  escortDetail.value = {};
}
const getEscortVisible = computed(() => {
  return cellValueFormatter(escortDetail.value.visible, visibleEnum);
})
const getEscortGender = computed(() => {
  return cellValueFormatter(escortDetail.value.gender, genderEnum);
})
const handleCloseEdit = () => {
  if (confirm('是否放弃编辑？')) {
    closeEditDialog();
  }
}
const closeEditDialog = () => {
  editDialogVisible.value = false;
  escortDetail.value = {};
  imgList.value = [];
  isAdd.value = false;
}
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  imageDialogVisible.value = true
}
const pictureAdd = (response, uploadFile) => {
  escortDetail.value.imgUrlList.push(response.data);
}
const handlePictureRemove = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, uploadFiles)
  handleRemove(uploadFile, 1);
}
const handleRemove = (uploadFile) => {
  let filePath;
  if (!uploadFile.response) {
    filePath = uploadFile.url;
  } else {
    filePath = uploadFile.response.data;
  }
  if (!filePath) {
    return;
  }
  axios.delete(BASE_URL + '/v1/file/delete',
      {params: {filePath: filePath}})
      .then((response) => {
        if (response.data.code === 2000) {
          ElMessage.success('删除成功！');
          let list = escortDetail.value.imgUrlList;
          list = list.filter(item => item !== filePath);
          escortDetail.value.imgUrlList = list;
        } else {
          ElMessage.error(response.data.message);
        }
      });
}
const saveEscort = () => {
  // console.log(videoFileList.value);
  // console.log(imgList.value);
  escortDetail.value.workingHoursFrom =
      escortDetail.value.timeRange[0];
  escortDetail.value.workingHoursTo =
      escortDetail.value.timeRange[1];
  axios.post(BASE_URL + 'v1/show/escort/save', escortDetail.value)
      .then(res => {
        if (res.data.code === 2000) {
          ElMessage.success('保存成功！');
          closeEditDialog();
          loadEscort();
        } else {
          ElMessage.error(res.data.message);
        }
      });
}
</script>

<style scoped>

</style>